package cn.yunyichina.provider.hisiface.main;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.yunyichina.provider.hisiface.http.HttpServerConfig;
import cn.yunyichina.provider.hisiface.http.HttpServerInitializer;
import cn.yunyichina.provider.hisiface.invoke.OutsideInvokeServiceFactory;

import com.alibaba.dubbo.container.Main;

/**
* 前置机调度中心服务子系统启动入口
* @author zhangkw
* @date 2016-07-29
*
*/
public class HisifaceApp {

	 private static final Logger logger = LoggerFactory.getLogger(HisifaceApp.class);
	
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		
		// 初始化spring
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		applicationContext.start();
		
		// 启动http
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				
				try {
					HttpServerConfig.getConfig().initHttpConfig();
					OutsideInvokeServiceFactory.initOpenserviceMap();
					httpServerStart();
				} catch (Exception e) {
					logger.error("启动http异常", e);
				}
			}
		}).run();
		
		// 启动dubbo
		Main.main(args);
    		
		logger.info("调度中心服务启动成功");
	}
	
	/**
	 * 启动http服务
	 */
	public static void httpServerStart() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(HttpServerConfig.getConfig().getnThreads());
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new HttpServerInitializer());
            int port = HttpServerConfig.getConfig().getPort();
            Channel ch = b.bind(port).sync().channel();
            String httpStr = HttpServerConfig.getConfig().isSsl() ? "https" : "http";
            logger.info("{}服务启动成功，绑定端口：{}", httpStr, port);
            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
	}
}
